package 算法.LeetCode91.每日打卡题目;

import java.util.Stack;

/**
 * @author: 谢君臣
 * @create: 2021-02-03 18:31
 * @founction: XXXX
 */
public class day04 {
    public static void main(String[] args) {
        String s = decodeString("qwer3[a2[fc]a2[c]]see");
        System.out.println(s);
    }

    public static String decodeString(String s) {
        StringBuffer str = new StringBuffer();
        Stack<Integer> num = new Stack<>();
        Stack<String> stack = new Stack<>();
        int i = 0;
        while (i < s.length()) {
            int k = 0;
            String re = "";
            if ('0' <= s.charAt(i) && '9' >= s.charAt(i)) {
                while (s.charAt(i) != '[') {
                    k = k * 10 + Integer.parseInt(s.substring(i, i + 1));
                    i++;
                }
                num.push(k);
            }else {
                if (s.charAt(i) == ']') {
                    k = num.pop();
                    if (num.empty()){
                        while (!stack.peek().equals("[")) {
                            re = stack.pop().concat(re);
                        }
                        stack.pop();
                        while (k-->0)
                            str.append(re);
                    }else {
                        while (!stack.peek().equals("[")) {
                            re = stack.pop().concat(re);
                        }
                        stack.pop();
                        while (k-->0)
                            stack.push(re);
                    }
                } else {
                    if (num.empty())
                        str.append(s.substring(i, i + 1));
                    else
                        stack.push(s.substring(i, i + 1));
                }
                i++;
            }
        }
        return str.toString();
    }
}